import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import Login from "../views/Login.vue";

Vue.use(VueRouter);


const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
	meta:{
		requireAuth:true
	}
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/about",
    name: "About",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/About.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});


router.beforeEach((to, from, next) => {
	const userName = sessionStorage.getItem('userName')
	let islogin = Boolean(userName);
  
	if(to.path == "/login"){
	  if(islogin){
		next("/home");
	  }else{
		next();
	  }
	}else{
	  // requireAuth:可以在路由元信息指定哪些页面需要登录权限
	  if(to.meta.requireAuth && islogin) {
		next();
	  }else{
		next("/login");
	  }
	}
  })

  const originalPush = VueRouter.prototype.push
  VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
  }
export default router;
